﻿using Aliyun.OSS;
using BCDto.Common.SystemExceptionRecord;
using BCService.Common.ExceptionService;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;

namespace BCService.Common.OSS
{
    public class OSSBucket:IOSSBucket
    {
        private readonly ISystemExceptionRecordService systemExceptionRecordService;
        private readonly IOSS oss;
        public OSSBucket(IOSS oss,ISystemExceptionRecordService systemExceptionRecordService)
        {
            this.oss = oss;
            this.systemExceptionRecordService = systemExceptionRecordService;
        }
        
        public bool CheckeBucketExists(string bucketName)
        {
            OssClient client = new OssClient(oss.GetEndpoint(), oss.GetAccessKeyId(), oss.GetAccessKeySecret());

            try
            {
                bool exists = client.DoesBucketExist(bucketName);
                return exists;
            }
            catch(Exception ex)
            {
                SystemExceptionRecordDto systemExceptionRecordDto = new SystemExceptionRecordDto();
                systemExceptionRecordDto.Data = JsonConvert.SerializeObject(ex.Data);
                systemExceptionRecordDto.Name = "检查OSS存储空间是否存在异常";
                systemExceptionRecordDto.Message = ex.Message;
                systemExceptionRecordDto.Source = ex.Source;
                systemExceptionRecordDto.StackTrace = ex.StackTrace;
                systemExceptionRecordDto.InnerException = JsonConvert.SerializeObject(ex.InnerException);
                this.systemExceptionRecordService.Create(systemExceptionRecordDto);
                return false;
            }
        }

        public Bucket CreateBucket(string bucketName)
        {
            OssClient client = new OssClient(oss.GetEndpoint(), oss.GetAccessKeyId(), oss.GetAccessKeySecret());
            return client.CreateBucket(bucketName);
        }

        public IEnumerable<Bucket> GetBuckets()
        {
            OssClient client = new OssClient(oss.GetEndpoint(), oss.GetAccessKeyId(), oss.GetAccessKeySecret());
            return client.ListBuckets();
        }
    }
}
